package com.sjzd.gateway;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@SpringBootApplication
@RestController
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("rewrite_route", r -> r.path("/sjzd/**")
                        .filters(f -> f.rewritePath("/sjzd", "/mclient01"))
                        .uri("http://localhost:8080"))
//                .route("path_route", r -> r.path("/hello")
//                        .filters(f -> f.prefixPath("/mclient01"))
//                        .uri("lb://mclient01:8080"))
                .route("fallback_route", r -> r.path("/error")
                        .filters(f -> f.circuitBreaker(c -> c.setName("gateway_circuit").setFallbackUri("forward:/fallback")))
                        .uri("http://localhost:6060"))
                .route("limit_route", r -> r
                        .path("/hello")
                        .filters(f -> f.prefixPath("/mclient01").requestRateLimiter().configure(c -> c.setRateLimiter(redisRateLimiter())))
                        .uri("http://localhost:8080"))
                .build();
    }

    @RequestMapping("/fallback")
    public String fallback() {
        return "fallback error";
    }

    @Bean
    RedisRateLimiter redisRateLimiter() {
        return new RedisRateLimiter(1, 3);
    }

    @Bean
    KeyResolver pathKeyResolver() {
        return (exchange) -> Mono.just(exchange.getRequest().getURI().getPath());
    }
}
